/* 
  行状态管理
*/
import $ from '@/common'
export default {
  state: {
    singleSelect: false
  },
  getters: {
    selectedLength(state, getters) {
      return getters.selectedData.length
    },
    selectedRows(state, getters) {
      var data = []
      for (let row of getters.selectedData) {
        if (row.data) {
          data.push(row.data)
        }
      }
      return data
    },
    selectedRow(state, getters) {
      return getters.selectedRows.length ? getters.selectedRows[0] : null
    },
    selectedIds(state, getters) {
      var data = []
      for (let row of getters.selectedData) {
        if (row.data & row.data.id !== undefined & row.data.id !== null) {
          data.push(row.data.id)
        }
      }
      return data
    },
    selectedId(state, getters) {
      return getters.selectedIds.length ? getters.selectedIds[0] : null
    },
    selectedData(state) {
      var data = []
      for (let i = 0; i < state.rows.length; i++) {
        let row = state.rows[i]
        if (row && row.check) {
          data.push({
            index: i,
            status: row,
            data: data[i]
          })
        }
      }
      return data
    },
    allCheck(state, getters) {
      return getters.selectedData.length === state.data.length
    }
  },
  actions: {
    checkToggle({state, commit}, index) {
      if (state.rows[index] && state.rows[index].check) {
        commit('checkRow', {
          index,
          value: false
        })
      } else {
        commit('checkRow', {
          index,
          value: true
        })
      }
    },
    checkAllRow({state, commit}, value) {
      for (let i = 0; i < state.data.length; i++) {
        commit('checkRow', {
          index: i,
        value})
      }
    },
    trHover({commit}, {index, value}) {
      commit('setStatus', {
        index,
        value,
        code: 'hover'
      })
    }
  },
  mutations: {
    setStatus(state, {value, index, code}) {
      if (!state.rows[index]) {
        $.set(state.rows, index, {
          [code]: value
        })
      } else {
        $.set(state.rows[index], code , value)
      }
    },
    checkRow(state, {value, index}) {
      if (!state.rows[index]) {
        $.set(state.rows, index, {
          check: value
        })
      } else {
        $.set(state.rows[index], 'check' , value)
      }
    },
    // 清除行状态数据
    restRowStatus(state) {
      var rows = []
      for (let i = 0; i < state.data.length; i++) {
        rows.push({})
      }
      $.set(state, 'rows', rows)
    },
    setSingleSelect(state, data) {
      state.singleSelect = data
    }
  }
}
